package com.wg.core.serialize.impl;

import com.google.protobuf.Message;
import com.wg.core.serialize.ISerializer;
import com.wg.core.serialize.SerializeType;

/**
 * ProtoBuf 序列化器
 *
 * @author 少爷123
 */
public class ProtoBufSerializer implements ISerializer {

    @Override
    public byte[] serialize(Object obj) throws Exception {
        if (obj instanceof Message) {
            return ((Message) obj).toByteArray();
        }
        throw new IllegalArgumentException("ProtoSerializer only supports protobuf Message objects");
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        if (!Message.class.isAssignableFrom(clazz)) {
            throw new IllegalArgumentException("ProtoSerializer only supports protobuf Message objects");
        }
        
        java.lang.reflect.Method method = clazz.getMethod("newBuilder");
        Message.Builder builder = (Message.Builder) method.invoke(null);
        builder.mergeFrom(data);
        return (T) builder.build();
    }

    @Override
    public int getType() {
        return SerializeType.PROTOBUF.getType();
    }
}
